import { defineStore } from 'pinia'
import { ref } from 'vue'
import { 
  getCartList, 
  addToCart, 
  updateCart, 
  removeCartItem, 
  clearCart,
  type CartItem 
} from '@/api/cart'

export const useCartStore = defineStore('cart', () => {
  // 购物车商品列表
  const cartItems = ref<CartItem[]>([])
  // 加载状态
  const loading = ref(false)

  // 获取购物车列表
  const fetchCart = async (userId: number) => {
    try {
      loading.value = true
      const response = await getCartList(userId)
      console.log('购物车API响应:', response)
      if (response.data) {
        cartItems.value = response.data
      }
      return response.data
    } catch (error: any) {
      console.error('获取购物车失败:', error)
      return []
    } finally {
      loading.value = false
    }
  }

  // 添加商品到购物车
  const add = async (userId: number, productId: number, quantity: number) => {
    try {
      loading.value = true
      const response = await addToCart(userId, productId, quantity)
      if (response.data) {
        // 重新获取购物车列表
        await fetchCart(userId)
      }
      return response.data
    } catch (error: any) {
      console.error('添加商品到购物车失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 更新商品数量
  const update = async (userId: number, productId: number, quantity: number) => {
    try {
      loading.value = true
      const response = await updateCart(userId, productId, quantity)
      if (response.data) {
        // 重新获取购物车列表
        await fetchCart(userId)
      }
      return response.data
    } catch (error: any) {
      console.error('更新购物车失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 删除商品
  const remove = async (userId: number, productId: number) => {
    try {
      loading.value = true
      const response = await removeCartItem(userId, productId)
      if (response.data) {
        // 重新获取购物车列表
        await fetchCart(userId)
      }
      return response.data
    } catch (error: any) {
      console.error('删除购物车商品失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 清空购物车
  const clear = async (userId: number) => {
    try {
      loading.value = true
      const response = await clearCart(userId)
      // 无论API返回什么，都清空本地购物车数据
      cartItems.value = []
      return response.data
    } catch (error: any) {
      console.error('清空购物车失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 清空状态
  const clearCartState = () => {
    cartItems.value = []
  }

  return {
    cartItems,
    loading,
    fetchCart,
    add,
    update,
    remove,
    clear,
    clearCartState
  }
})